package com.itheima.controller;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.layout.LayoutResult;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.renderer.TableRenderer;

import java.io.IOException;
import java.util.List;

/**
 * <h1>ysm</h1>
 *
 * @author <a href="11n_yd2h5e1jx8@dingtalk.com">叶世铭</a>
 * @since 2024/1/9
 */
public class HeaderFooterHandler implements IEventHandler {

    private final Table headerTable;

    private final List<String> headList;

    public HeaderFooterHandler(Table headerTable, List<String> headList) {
        this.headerTable = headerTable;
        this.headList = headList;
    }

    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        int pageNumber = pdfDoc.getNumberOfPages();
        try {
            addTableHead(headerTable,headerTable.getNumberOfColumns(),headList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void addTableHead(Table table, int column, List<String> tableHeadList) throws IOException {
        PdfFont font = PdfFontFactory.createFont("src/main/resources/AlimamaShuHeiTi-Bold.ttf", PdfEncodings.IDENTITY_H);
        for (int i = 0; i < column; i++) {
            Paragraph content = new Paragraph(tableHeadList.get(i)).setFont(font).setFontSize(10L).setTextAlignment(TextAlignment.CENTER);
            table.addCell(new Cell().add(content).setKeepTogether(true));
        }
    }
}